<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="契约类型" prop="contractType">
        <el-select v-model="queryParams.contractType" placeholder="请选择契约类型" clearable>
          <el-option
              v-for="dict in lease_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间" prop="startDate">
        <el-date-picker clearable
                        v-model="queryParams.startDate"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endDate">
        <el-date-picker clearable
                        v-model="queryParams.endDate"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="租约客户" prop="customerName" clearable>
        <el-select
            v-model="queryParams.customerName"
            placeholder="请选择租户"
            clearable
        >
          <el-option
              v-for="customer in customer"
              :key="customer.customerId"
              :label="customer.customerName"
              :value="customer.customerName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="租约房间" prop="roomName" clearable>
        <el-select
            v-model="queryParams.roomName"
            placeholder="请选择房间"
            clearable
        >
          <el-option
              v-for="room in room"
              :key="room.roomId"
              :label="room.roomName"
              :value="room.roomName"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['lease:contract:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['lease:contract:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['lease:contract:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['lease:contract:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="contractList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" type="index" width="50" align="center" prop="contractId"/>
      <el-table-column label="租户名称" align="center" prop="customerName"/>
      <el-table-column label="房间名称" align="center" prop="roomName"/>
      <el-table-column label="契约类型" align="center" prop="contractType">
        <template #default="scope">
          <dict-tag :options="lease_type" :value="scope.row.contractType"/>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['lease:contract:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['lease:contract:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!--  TODO 添加或修改契约对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="contractRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="租客名称" prop="customerName" v-if="form.contractId === null">
          <el-select v-model="form.customerName" placeholder="请选择前端用户" clearable v-if="isAdd">
            <el-option
                v-for="customer in customer"
                :key="customer.customerId"
                :label="customer.customerName"
                :value="customer.customerName"
            />
          </el-select>
          <el-input
              v-if="!isAdd"
              v-model="form.customerName"
              style="width: 220px"
              :readonly="true"
              placeholder="租客名称不可更改，您可以选择退租"
              @click="showMessage"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="公寓名称" prop="flatsName" v-if="form.contractId === null">
          <el-select

              v-model="form.flatsName"
              placeholder="请选择公寓"
              clearable
              @change="updatePhoneNumberAndGetRoom"
          >
            <el-option
                v-for="flats in flatsList"
                :key="flats.flatsId"
                :label="flats.flatsName"
                :value="flats.flatsName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="签约房间" prop="roomName" clearable>
          <el-tooltip v-if="!form.flatsName && isAdd" content="请先选择公寓" placement="top">
            <el-select
                v-model="form.roomName"
                placeholder="请选择房间"
                clearable
                :disabled="!form.flatsId"
            >
            </el-select>
          </el-tooltip>
          <el-select
              v-if="form.flatsName"
              v-model="form.roomName"
              placeholder="请选择房间"
              clearable
          >
            <el-option
                v-for="room in roomBy"
                :key="room.roomName"
                :label="room.roomName"
                :value="room.roomName"
            />
          </el-select>
          <el-input
              v-if="!isAdd"
              v-model="form.roomName"
              style="width: 220px"
              :readonly="true"
              placeholder="房间名称不可更改，您可以选择取消预约"
              @click="showMessage"
          />
        </el-form-item>
        <el-form-item label="租期" prop="contractTerm">
          <el-select v-model="form.contractTerm" placeholder="请选择">
            <el-option
                v-for="term in lease_term"
                :key="term.value"
                :label="term.label"
                :value="term.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="契约类型" prop="contractType">
          <el-select v-model="form.contractType" placeholder="请选择契约类型">
            <el-option
                v-for="dict in lease_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startDate">
          <el-date-picker
              clearable
              v-model="form.startDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择开始时间"
              @change="updateEndDate">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endDate">
          <el-date-picker clearable
                          v-model="form.endDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择结束时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Contract">
import {listContract, getContract, delContract, addContract, updateContract} from "@/api/lease/contract";
import {ref} from "vue";
import {listProvince} from "@/api/apartment/location.js";
import {listCustomer} from "@/api/system/customer.js";
import {listRoom} from "@/api/apartment/room.js";
import {getFlatsRoom} from "@/api/apartment/flatsroom.js";
import {listFlats} from "@/api/apartment/flats.js";
import {ElMessage} from "element-plus";

const {proxy} = getCurrentInstance();
const {lease_type,lease_term} = proxy.useDict('lease_type','lease_term');

const contractList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const customer = ref([]);
const room = ref([]);
const roomBy = ref([]);
const flatsList = ref([]);
const isAdd = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    customerName: undefined,
    flatsName: undefined,
    roomName: undefined,
    contractType: null,
    contractTerm:null,
    startDate: null,
    endDate: null
  },
  rules: {
    customerName: [{required: true, message: "租客名称不能为空", trigger: "blur"}],
    flatsName: [{required: true, message: "公寓名称不能为空", trigger: "blur"}],
    roomName: [{required: true, message: "房间名称不能为空", trigger: "blur"}],
    contractType: [{required: true, message: "契约类型不能为空", trigger: "blur"}],
    contractTerm: [{required: true, message: "租期不能为空", trigger: "blur"}],
    startDate: [{required: true, message: "开始时间不能为空", trigger: "blur"}],
    endDate: [{required: true, message: "结束时间不能为空", trigger: "blur"}]
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 租客列表 */
function getCustomerList() {
  loading.value = true;
  listCustomer(queryParams.value).then(response => {
    customer.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 房间列表 */
function getRoomList() {
  loading.value = true;
  listRoom(queryParams.value).then(response => {
    room.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询契约列表 */
function getList() {
  loading.value = true;
  listContract(queryParams.value).then(response => {
    contractList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    contractId: null,
    customerName: null,
    roomName: null,
    contractType: null,
    startDate: null,
    endDate: null
  };
  proxy.resetForm("contractRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.contractId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  isAdd.value = true;
  open.value = true;
  title.value = "添加契约";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  isAdd.value = false;
  reset();
  const _contractId = row.contractId || ids.value
  getContract(_contractId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改契约";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["contractRef"].validate(valid => {
    if (valid) {
      if (form.value.contractId != null) {
        updateContract(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addContract(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _contractIds = row.contractId || ids.value;
  proxy.$modal.confirm('是否确认删除契约编号为"' + _contractIds + '"的数据项？').then(function () {
    return delContract(_contractIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('lease/contract/export', {
    ...queryParams.value
  }, `contract_${new Date().getTime()}.xlsx`)
}

function updatePhoneNumberAndGetRoom() {
  const selectedFlat = flatsList.value.find(flat => flat.flatsName === form.value.flatsName);
  if (selectedFlat) {
    getRoomsByFlatId(selectedFlat.flatsId);
  } else {
    roomBy.value = []; // 清空房间列表
  }
}

function getRoomsByFlatId(flatsId) {
  loading.value = true;
  getFlatsRoom(flatsId).then(response => {
    roomBy.value = response.rows; // 确保将房间数据赋值给 roomBy
    total.value = response.total;
    loading.value = false;
  }).catch(error => {
    loading.value = false; // 确保在出错时也停止加载
    console.error("获取房间数据失败:", error);
  });
}

/** 公寓列表 */
function getFlatsList() {
  // 这里需要调用 API 获取公寓列表
  // 假设有一个 API 方法 listFlats
  loading.value = true;
  listFlats().then(response => {
    flatsList.value = response.rows; // 假设返回的公寓数据在 rows 中
    loading.value = false;
  });
}

function updateEndDate() {
  if (form.value.contractType === 'new' || form.value.contractType === 'renewal') {
    if (form.value.startDate) {
      const startDate = new Date(form.value.startDate);
      const endDate = new Date(startDate.setMonth(startDate.getMonth() + 1));
      form.value.endDate = endDate.toISOString().split('T')[0];
    }
  }
}
function showMessage() {
  ElMessage({
    message: '不可更改，您可以选择取消预约',
    type: 'warning',  // 可以是 'success', 'warning', 'info', 或 'error'
    duration: 3000,   // 持续时间，单位为毫秒
    center: true      // 文字居中
  });
}

getList();
getCustomerList();
getRoomList();
getFlatsList();
</script>
